<template>
  <div class="h-11 m:h-14 flex items-center justify-center border-b border-white/20 shrink-0">
    <h1 class="text-lg font-bold text-[#ececf1]">{{ mainStore.pageTitle }}</h1>
  </div>
  <div class="sider-container h-[calc(100%-44px)] m:h-[calc(100%-56px)]">
    <div class="option-space flex flex-col gap-1.5 flex-1 overflow-auto">
      <div class="newchat-box px-2.5 pt-2.5">
        <n-button class="w-full h-11 justify-start" ghost :focusable="false" @click="gotoNewChat">
          <template #icon>
            <n-icon :component="AddOutline" :size="18" />
          </template>
          新对话窗口
        </n-button>
      </div>
      <div
        v-if="chatStore.msgList.length === 0 && !chatStore.listLoading && userStore.isLogin"
        class="px-2.5 flex justify-center cursor-pointer items-center gap-1 hover:text-primary text-base mt-1"
        @click="chatStore.getMsgList"
      >
        <n-icon class="ease-linear mt-[-2px]" :component="RefreshCircleOutline" size="24" />
        刷新会话列表
      </div>
      <n-scrollbar trigger="none" class="chat-block pl-2.5 h-[calc(100%-54px)]">
        <n-spin :show="chatStore.listLoading" description="加载中" class="pr-2.5">
          <n-button
            v-for="item in msgList"
            :key="item.conversation_id"
            quaternary
            :focusable="false"
            :class="['my-1', { 'bg-dark': $route.params.id === item.conversation_id }]"
            @click="changeChat(item)"
          >
            <template #icon>
              <n-icon :component="ChatboxOutline" :size="18" />
            </template>
            <div class="w-full flex items-center justify-between">
              <n-ellipsis style="max-width: 100%" :tooltip="false">
                {{ item.title }}
              </n-ellipsis>
              <n-icon
                :component="TrashOutline"
                :size="16"
                title="删除对话"
                :class="[{ visible: $route.params.id === item.conversation_id }]"
                @click.stop="delChat(item.conversation_id)"
              />
            </div>
          </n-button>
        </n-spin>
      </n-scrollbar>
    </div>
    <n-space class="option-space mx-2.5 mt-1 py-2 border-t border-white/20 shrink-0" vertical>
      <n-button
        v-if="!(isMobile() && isWeiXin()) && !isMini"
        quaternary
        :focusable="false"
        @click="emit('openWechatOfficial')"
      >
        <template #icon>
          <n-icon :component="LogoWechat" />
        </template>
        微信公众号
      </n-button>
      <n-button
        v-if="!isMini"
        quaternary
        :focusable="false"
        tag="a"
        href="https://work.weixin.qq.com/kfid/kfc91f6be6a3e837336"
        target="_blank"
      >
        <template #icon>
          <n-icon :component="HeadsetOutline" />
        </template>
        联系客服
      </n-button>
      <n-button
        v-if="userStore.isLogin && !(isMobile() && isWeiXin()) && !isMini"
        quaternary
        :focusable="false"
        @click="switchRouter('/openapi')"
      >
        <template #icon>
          <n-icon :component="CodeSlashOutline" />
        </template>
        开放API
      </n-button>
      <n-button
        v-if="userStore.isLogin && +new Date(userStore.expiration_at) >= +new Date()"
        quaternary
        :focusable="false"
        @click="switchRouter('/invite')"
      >
        <template #icon>
          <n-icon :component="ShareSocialOutline" />
        </template>
        推广返礼
      </n-button>
      <n-button v-if="userStore.isLogin" quaternary :focusable="false" @click="emit('openCardActive')">
        <template #icon>
          <n-icon :component="BarcodeOutline" />
        </template>
        卡密兑换
      </n-button>
      <n-button v-if="userStore.isLogin" quaternary :focusable="false" @click="switchRouter('/plan')">
        <template #icon>
          <n-icon :component="BagHandleOutline" />
        </template>
        套餐订阅
      </n-button>
      <n-button v-if="!userStore.isLogin" quaternary :focusable="false" @click="emit('openWechatLogin')">
        <template #icon>
          <n-icon :component="EnterOutline" />
        </template>
        立即登录
      </n-button>
      <div v-else class="px-4 pb-3 pt-1 flex gap-3 cursor-pointer" @click="switchRouter('/plan')">
        <img :src="userStore.head_img" width="44" height="44" class="rounded shrink-0" alt="" />
        <div class="w-full flex flex-col items-start justify-between">
          <div class="w-full flex justify-between">
            <img
              v-if="userStore.edition === 'plus'"
              class="w-7"
              :src="getImageUrl('chat', 'vip_active')"
              alt="vip-active"
            />
            <img v-else class="w-7" :src="getImageUrl('chat', 'vip_default')" alt="vip-default" />
            <n-icon title="退出登录" size="20" class="cursor-pointer text-[#ececf1]" @click.stop="userLogout">
              <PowerOutline />
            </n-icon>
          </div>
          <n-ellipsis class="max-w-[150px] text-base leading-none text-[#ececf1]" :tooltip="false">
            {{ userStore.nickname }}
          </n-ellipsis>
        </div>
      </div>
    </n-space>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { deleteMessage } from '@api/chatApi'
import { storeToRefs } from 'pinia'
import {
  TrashOutline,
  AddOutline,
  ChatboxOutline,
  EnterOutline,
  BagHandleOutline,
  PowerOutline,
  LogoWechat,
  HeadsetOutline,
  ShareSocialOutline,
  CodeSlashOutline,
  BarcodeOutline,
  RefreshCircleOutline,
} from '@vicons/ionicons5'
import { useUserStore, useMainStore, useChatStore } from '@/store'
import { useDialog } from '@/hook/useDialog'
import { getImageUrl, isMobile, isWeiXin, isMiniProgram } from '@/utils'

const router = useRouter()
const isMini = ref(true)

isMiniProgram().then(bool => {
  isMini.value = bool
})

const mainStore = useMainStore()
const userStore = useUserStore()
const chatStore = useChatStore()

const { msgList } = storeToRefs(chatStore)

const emit = defineEmits(['register', 'openWechatLogin', 'openWechatOfficial', 'openCardActive'])

const waitreply = () => {
  useDialog({
    title: '提示',
    content: 'AI正在回复中，请等待AI回复完毕。',
    type: 'warning',
    icon: true,
    positive: '继续等待',
    negative: '',
    confirm() {},
  })
}

const switchRouter = path => {
  if (chatStore.getting) return waitreply()
  router.push(path)
  chatStore.closeChatSiderDrawer()
}

const gotoNewChat = () => {
  if (chatStore.getting) return waitreply()
  chatStore.openNewChat()
}

const changeChat = item => {
  if (chatStore.getting) return waitreply()
  chatStore.setDocTitle(item.title)
  chatStore.showChatSiderDrawer = false
  chatStore.message = ''
  chatStore.isNewChat = false
  chatStore.selectRoleKey = item.chat_role
  router.replace(`/chat/${item.conversation_id}`)
}

const userLogout = () => {
  if (chatStore.getting) return waitreply()
  userStore.logout()
}

const delChat = id => {
  if (chatStore.getting) return waitreply()
  let delDialog = useDialog({
    title: '删除',
    content: '是否删除该会话？',
    type: 'error',
    icon: true,
    async confirm() {
      await submitDelete()
    },
    cancel() {},
  })
  const submitDelete = async () => {
    const res = await deleteMessage({ conversation_id: [id] })
    if (res?.statusCode === 200) {
      delDialog && delDialog.destroy()
      delDialog = null
      chatStore.openNewChat()
      chatStore.msgList.forEach((item, index) => {
        if (item.conversation_id === id) {
          chatStore.msgList.splice(index, 1)
        }
      })
      $message.success(res.msg, { duration: 1500 })
    }
  }

  // if (delDialog) {
  //   delDialog.onkeydown = event => {
  //     if (window.event) {
  //       event = window.event
  //     }
  //     const keycode = event.charCode || event.keyCode
  //     if (keycode == 13) {
  //       submitDelete()
  //     }
  //   }
  // }
}
</script>

<style lang="less" scoped>
.sider-container {
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  &:deep(.newchat-box) {
    .n-button--ghost {
      .n-button__state-border,
      .n-button__border {
        border-color: #55575e;
      }
    }

    .n-button:not(.n-button--disabled):hover {
      background-color: #2b2c2f;
    }
  }

  &:deep(.option-space) {
    .chat-block {
      .n-spin-content {
        .n-button {
          &:hover {
            .n-button__content .n-icon {
              visibility: visible;
            }
          }

          .n-button__content {
            width: 100%;

            .n-icon {
              visibility: hidden;
            }
          }
        }
      }
    }

    .n-button {
      width: 100%;
      height: 44px;
      color: #ececf1;
      justify-content: flex-start;

      .n-button__icon {
        font-size: 22px;
        margin-right: 15px;
        margin-top: 3px;
      }
    }

    .n-button:not(.n-button--disabled):hover {
      background-color: #2a2b32;
    }
  }

  &:deep(.n-dialog__content) {
    margin-top: 12px;

    .wechat-card {
      .n-card__content {
        padding: 20px 0 6px;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
      }
    }
  }
}
</style>
